#include "ws2812b.h"

#define F_CPU 20000000UL
#include <util/delay.h>

#define RST 120
#define SET_BIT(PORT, POS, VALUE) PORT = (PORT & ~(1 << POS)) | (VALUE << POS)
#define GET_BIT(PORT, POS) (PORT & (1 << POS)) >> POS
#define WAIT_BIG_ONE    ({asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");})
#define WAIT_SMALL_ONE  ({asm("nop");})

#define WAIT_SMALL_ZERO ({asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");})
#define WAIT_BIG_ZERO   ({asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");})

void initLEDs()
{
    PORTA.OUT = 0x00;
}

//void inline SendBit(uint8_t BIT)
//{
//    if(BIT)
//    {
//        PORTA.OUT = 0x04;
//        WAIT_BIG_ONE;
//        PORTA.OUT = 0x00;
//        WAIT_SMALL_ZERO;
//    }
//    else
//    {
//        PORTA.OUT = 0x04;
//        WAIT_SMALL_ONE;
//        PORTA.OUT = 0x00;
//        WAIT_BIG_ZERO; 
//    }
//}




void inline SendBit(uint8_t BIT)
//void SendBit(uint8_t BIT)
 {
	 PORTA.OUT = 0x04;
	 if (BIT)
     WAIT_BIG_ONE;
	 else
	 WAIT_SMALL_ONE;

	 PORTA.OUT = 0x00;
	 if (BIT)
	 WAIT_SMALL_ZERO;
	 else
	 WAIT_BIG_ZERO;
}

void flush()
{
    PORTA.OUT = 0x00;
    _delay_us(RST);
}

void setColor(uint8_t red, uint8_t green, uint8_t blue)
{
    SendBit(GET_BIT(red, 7));asm("nop");asm("nop");
    SendBit(GET_BIT(red, 6)); asm("nop");asm("nop");asm("nop");
    SendBit(GET_BIT(red, 5)); asm("nop"); asm("nop");asm("nop");  
    SendBit(GET_BIT(red, 4)); asm("nop"); asm("nop");asm("nop"); asm("nop"); 
    SendBit(GET_BIT(red, 3)); asm("nop"); asm("nop");asm("nop");  
    SendBit(GET_BIT(red, 2)); asm("nop"); asm("nop");asm("nop");
    SendBit(GET_BIT(red, 1)); asm("nop"); asm("nop");asm("nop"); 
    SendBit(GET_BIT(red, 0)); asm("nop");asm("nop");asm("nop");  

    SendBit(GET_BIT(green, 7));
    SendBit(GET_BIT(green, 6));asm("nop");
    SendBit(GET_BIT(green, 5));asm("nop");
    SendBit(GET_BIT(green, 4));asm("nop");
    SendBit(GET_BIT(green, 3));asm("nop");asm("nop");
    SendBit(GET_BIT(green, 2));asm("nop");
    SendBit(GET_BIT(green, 1));asm("nop");
    SendBit(GET_BIT(green, 0));asm("nop");asm("nop");

    SendBit(GET_BIT(blue, 7));asm("nop");
    SendBit(GET_BIT(blue, 6));asm("nop");
    SendBit(GET_BIT(blue, 5));asm("nop");
    SendBit(GET_BIT(blue, 4));asm("nop");
    SendBit(GET_BIT(blue, 3));asm("nop");
    SendBit(GET_BIT(blue, 2));asm("nop");
    SendBit(GET_BIT(blue, 1));asm("nop");
    SendBit(GET_BIT(blue, 0));
}